package org.csu.code.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.tomcat.jni.Time;
import org.csu.code.api.common.CommonResponse;
import org.csu.code.api.entity.*;
import org.csu.code.api.persistence.*;
import org.csu.code.api.service.OrderService;
import org.csu.code.api.vo.OrderVO;
import org.csu.code.api.vo.typeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @Autowired
    private LineItemMapper lineItemMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private FarmMapper farmMapper;
    @Autowired
    private SequenceMapper sequenceMapper;

    @Override
    public CommonResponse<List<OrderVO>> getOrdersByUserId(int userId) {
        QueryWrapper<Order> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("userid",userId);
        List<Order> orderList = orderMapper.selectList(queryWrapper);
        if(orderList.isEmpty()) {
            return CommonResponse.createForError("没有用户的订单信息");
        }
        List<OrderVO> orderVOList = new ArrayList<>();
        for(Order order : orderList){
            OrderVO orderVO = orderToOrderVO(order);
            orderVOList.add(orderVO);
        }
        return CommonResponse.createForSuccess(orderVOList);
    }

    @Override
    public CommonResponse<OrderVO> getOrderByOrderId(int orderId) {
        Order order = orderMapper.selectById(orderId);
        if(order==null)
        {
            return CommonResponse.createForError("没有该订单号的订单信息");
        }
        OrderVO orderVO = orderToOrderVO(order);
        return CommonResponse.createForSuccess(orderVO);
    }

    @Override
    public OrderVO orderToOrderVO(Order order) {
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderId(order.getOrderId());
        orderVO.setUserId(order.getUserId());
        orderVO.setFarmId(order.getFarmId());
        orderVO.setShipAddress1(order.getShipAddress1());
        orderVO.setShipAddress2(order.getShipAddress2());
        orderVO.setShipCity(order.getShipCity());
        orderVO.setShipState(order.getShipState());
        orderVO.setShipZip(order.getShipZip());
        orderVO.setShipCountry(order.getShipCountry());
        orderVO.setBillAddress1(order.getBillAddress1());
        orderVO.setBillAddress2(order.getBillAddress2());
        orderVO.setBillCity(order.getBillCity());
        orderVO.setBillState(order.getBillState());
        orderVO.setBillZip(order.getBillZip());
        orderVO.setBillCountry(order.getBillCountry());
        orderVO.setCourier(order.getCourier());
        orderVO.setTotalPrice(order.getTotalPrice());
        orderVO.setBillToFirstName(order.getBillToFirstName());
        orderVO.setBillToLastName(order.getBillToLastName());
        orderVO.setShipToFirstName(order.getShipToFirstName());
        orderVO.setShipToLastName(order.getShipToLastName());
        orderVO.setOrderDate(order.getOrderDate());
        orderVO.setLocation(order.getLocation());
        orderVO.setPaid(order.isPaid());
        Rent rent = null;

        OrderStatus orderStatus = orderStatusMapper.selectById(order.getOrderId());
        orderVO.setStatus(orderStatus.getStatus());

        QueryWrapper<LineItem> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("orderid",order.getOrderId());
        List<LineItem> lineItems = lineItemMapper.selectList(queryWrapper);
        orderVO.setLineItems(lineItems);

        return orderVO;
    }

    @Override
    public CommonResponse<String> changeOrderStatus(int orderId, typeVO type) {
        Order order = orderMapper.selectById(orderId);
        if(order==null){
            return CommonResponse.createForError("订单不存在！");
        }
        if(type.getType() == 1){
            //change payment status
            order.setPaid(true);
            orderMapper.updateById(order);
            return CommonResponse.createForSuccess("订单支付成功！");
        }
        if(type.getType() == 2){
            OrderVO orderVO = orderToOrderVO(order);
            OrderStatus orderStatus = orderStatusMapper.selectById(orderId);
            orderStatus.setStatus("delivered");
            for (int i = 0; i < orderVO.getLineItems().size(); i++) {
                int itemId = orderVO.getLineItems().get(i).getItemId();
                System.out.println("itemId is "+itemId);
                int boughtAmount = orderVO.getLineItems().get(i).getQuantity();
                System.out.println("buying amount is "+boughtAmount);
                Item item = itemMapper.selectById(itemId);
                int stock = item.getStock();
                System.out.println("now stock is "+stock);
                stock = stock-boughtAmount;
                item.setStock(stock);
                itemMapper.update(item, Wrappers.<Item>query().eq("itemid",itemId));
            }
            orderStatusMapper.updateById(orderStatus);
            return CommonResponse.createForSuccess("订单状态修改成功");
        }
        return CommonResponse.createForError("请求体需为1或2");
    }


    @Override
    public int getNextId(String name) {
        Sequence sequence = new Sequence(name, -1);
        QueryWrapper<Sequence> sequenceQueryWrapper = new QueryWrapper<>();
        sequenceQueryWrapper.like("name", name);
        sequence = sequenceMapper.selectOne(sequenceQueryWrapper);
        if(sequence == null){
            throw new RuntimeException("Error:"+name+"is null");
        }
        Sequence parameterObject = new Sequence(name, sequence.getNextId() + 1);
        sequenceMapper.updateById(parameterObject);
        return sequence.getNextId();
    }

    @Override
    public CommonResponse<OrderVO> addOrder(OrderVO orderVO) {
        Order order = new Order();
        int orderId = getNextId("ordernum");
        order.setOrderId(orderId);
        order.setUserId(orderVO.getUserId());
        order.setFarmId(orderVO.getFarmId());
        Account account = accountMapper.selectById(orderVO.getUserId());
        order.setShipAddress1(account.getAddress1());
        order.setShipAddress2(account.getAddress2());
        order.setShipCity(account.getCity());
        order.setShipState(account.getProvince());
        order.setShipZip(account.getZip());
        order.setShipCountry(account.getCountry());
//        System.out.println(orderVO.toString());
        Farm farm = farmMapper.selectById(orderVO.getFarmId());
//        System.out.println(farm.toString());
        Account account1 = accountMapper.selectById(farm.getUserId());
        order.setBillAddress1(account1.getAddress1());
        order.setBillAddress2(account1.getAddress2());
        order.setBillCity(account1.getCity());
        order.setBillState(account1.getProvince());
        order.setBillZip(account1.getZip());
        order.setBillCountry(account1.getCountry());
        order.setCourier(orderVO.getCourier());
        order.setTotalPrice(orderVO.getTotalPrice());
        order.setBillToFirstName(account1.getFirstName());
        order.setBillToLastName(account1.getLastName());
        order.setShipToFirstName(account.getFirstName());
        order.setShipToLastName(account.getLastName());
        order.setOrderDate(new Date());
        order.setLocation(orderVO.getLocation());
        order.setPaid(false);
        System.out.println(order.toString());
        int insertOrder = orderMapper.insert(order);

        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setStatus("not delivered");
        orderStatus.setOrderId(orderId);
        orderStatus.setLineNum(orderVO.getOrderId());
        orderStatus.setTimestamp(new Date());
        int insertOrderStatus = orderStatusMapper.insert(orderStatus);

        int insertLineItem = 0;
        if(orderVO.getLineItems()!=null) {
            for (int i = 0; i < orderVO.getLineItems().size(); i++) {
                LineItem lineItem = new LineItem();
                lineItem.setOrderId(orderId);
                lineItem.setLineNumber(i + 1);
                lineItem.setItemId(orderVO.getLineItems().get(i).getItemId());
                lineItem.setQuantity(orderVO.getLineItems().get(i).getQuantity());
                System.out.println("lineItem id is: "+lineItem.getItemId());
                Item item = itemMapper.selectById(lineItem.getItemId());
                System.out.println("item is: "+item.toString());
                lineItem.setUnitPrice(item.getListPrice());
                System.out.println("lineItem is: "+lineItem.toString());
                insertLineItem = lineItemMapper.insert(lineItem);
                if (insertLineItem == 0)
                    break;
            }
        }
        if(insertOrder==1&&insertOrderStatus==1&&insertLineItem==1) {
            return CommonResponse.createForSuccess("创建订单成功",orderVO);
        }else {
            return CommonResponse.createForError("创建订单失败");
        }
    }

    public CommonResponse<List<OrderVO>> searchOrderList(String keyword){
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.like("orderid",keyword);
        List<Order> orders = orderMapper.selectList(orderQueryWrapper);
        List<OrderVO> orderVOs = new ArrayList<>();
        for (Order order:orders){
            OrderVO orderVO = orderToOrderVO(order);
            orderVOs.add(orderVO);
        }
        return CommonResponse.createForSuccess(orderVOs);
    }

}
